import '@/assets/css/index.less';
import { getUserInfoList} from '@/services/groupNumber';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType } from '@ant-design/pro-table';
import { useLocation } from 'umi';
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn'
import { getWebSiteInfo} from '@/services/linkManager';
import {Button, Col, DatePicker, Form, Input, Row, Select, Table, Tabs, TabsProps, Tag} from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import { getTopicInfoList } from '@/services/topic';
import { getCategoryList } from '@/services/category';
import {
  countByAuthor,
  countByCatName,
  countByGroup,
  countByReviewer,
} from '@/services/statistics';
import {SearchOutlined, UndoOutlined} from "@ant-design/icons";
import {LocalFormat} from "@/utils/localHelper";
const { RangePicker } = DatePicker;

const TableList: React.FC = (props) => {
  const location = useLocation();
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.UserListItem>();
  const [selectedRows, setSelectedRows] = useState<API.UserListItem[]>();

  //用户审核弹框
  const [userAuditsOpen, setUserAuditsOpen] = useState<boolean>(false);
  //部门下拉框
  const [groupOptions, setGroupOptions] = useState([]);
  //默认下拉部门
  const [groupId, setGroupId] = useState<number>(location.state?.groupId);
  //查询list
  const [dataList, setDataList] = useState([]);
  const [categoryOptions, setCategoryOptions] = useState([]);
  const [currentTab, setCurrentTab] = useState('1');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const colors = ['#3b5999', '#55acee', '#40a9ff', 'geekblue'];
  //分页
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: 40,
  });

  const [columns, setColumn] = useState<any>([]);
  //查询结果columns
  const getColumns = (type: any) => {
    let colums = [];
    switch (type) {
      case '1':
        setColumn([
          {
            title: '内容标题',
            align: 'center',
            dataIndex: 'title',
            width: '20%',
          },
          {
            title: '所属栏目',
            align: 'center',
            dataIndex: 'classifyName',
            // render: (_, record) =>
            //   [record.classifyName.split(",").map((item, index) =>
            //     <Tag color={colors[index]}>
            //       {item}
            //     </Tag>,
            //   )]
          },

          {
            title: '作者',
            align: 'center',
            dataIndex: 'createBy',
          },
          {
            title: '审核人',
            align: 'center',
            dataIndex: 'reviewer',
          },

          {
            title: '审核时间',
            align: 'center',
            dataIndex: 'shsj',
          },
          {
            title: '审核情况',
            align: 'center',
            dataIndex: 'zt',
          },
          {
            title: '操作时间',
            align: 'center',
            dataIndex: 'updateTime',
          },
          // {
          //   title: '操作',
          //   align: 'center',
          //   dataIndex: 'option',
          //   render: (_, record) => {
          //     return <a>11</a>;
          //   },
          // },
        ]);
        break;
      case '2':
        setColumn([
          {
            title: '栏目名称',
            align: 'left',
            dataIndex: 'catName',
            width: '20%',
          },
          {
            title: '内容数量',
            align: 'center',
            dataIndex: 'contentAmount',
          },
          {
            title: '内容比例',
            align: 'center',
            dataIndex: 'contentRatio',
          },
          {
            title: '浏览量',
            align: 'center',
            dataIndex: 'visitNum',
          },
          {
            title: '浏览比例',
            align: 'center',
            dataIndex: 'visitRatio',
          },
          // {
          //   title: '操作',
          //   align: 'center',
          //   dataIndex: 'option',
          //   render: (_, record) => {
          //     return <a>查看详情</a>;
          //   },
          // },
        ]);
        break;
      case '3':
        setColumn([
          {
            title: '部门名称',
            align: 'center',
            dataIndex: 'groupName',
          },
          {
            title: '内容数量',
            align: 'center',
            dataIndex: 'contentAmount',
          },
          {
            title: '内容比例',
            align: 'center',
            dataIndex: 'contentRatio',
          },
          {
            title: '浏览量',
            align: 'center',
            dataIndex: 'visitNum',
          },
          {
            title: '浏览比例',
            align: 'center',
            dataIndex: 'visitRatio',
          },
          // {
          //   title: '操作',
          //   align: 'center',
          //   dataIndex: 'option',
          //   render: (_, record) => {
          //     return <a>查看详情</a>;
          //   },
          // },
        ]);
        break;
      case '4':
        setColumn([
          {
            title: '作者',
            align: 'center',
            dataIndex: 'authorName',
          },
          {
            title: '内容数量',
            align: 'center',
            dataIndex: 'contentAmount',
          },
          {
            title: '内容比例',
            align: 'center',
            dataIndex: 'contentRatio',
          },
          {
            title: '浏览量',
            align: 'center',
            dataIndex: 'visitNum',
          },
          {
            title: '浏览比例',
            align: 'center',
            dataIndex: 'visitRatio',
          },
          // {
          //   title: '操作',
          //   align: 'center',
          //   dataIndex: 'option',
          //   render: (_, record) => {
          //     return <a>查看详情</a>;
          //   },
          // },
        ]);
        break;
      case '5':
        setColumn([
          {
            title: '审核人',
            align: 'center',
            dataIndex: 'reviewerName',
          },
          {
            title: '审核数量',
            align: 'center',
            dataIndex: 'reviewAmount',
          },
          {
            title: '审核比例',
            align: 'center',
            dataIndex: 'reviewRatio',
          },
          {
            title: '审核平均时间',
            align: 'center',
            dataIndex: 'showTm',
          },
          // {
          //   title: '操作',
          //   align: 'center',
          //   dataIndex: 'option',
          //   render: (_, record) => {
          //     return <a>查看详情</a>;
          //   },
          // },
        ]);
        break;
      default:
        break;
    }
  };
  const getCategory = async () => {
    const category = await getCategoryList({
      type: 'topic',
    });
    let categoryOptions = [];
    category.data &&
      category.data.map((item) =>
        categoryOptions.push({
          label: item.name,
          value: item.id,
        }),
      );
    setCategoryOptions(categoryOptions);
  };
  const [isFlow,setIsFlow] = useState()
  const getIsFlow = async()=>{
    const {data} = await getWebSiteInfo()
    setIsFlow(data.isFlow)
  }
  useEffect(() => {
    getColumns('1');
    //获取组list
    getCategory();
    getIsFlow()
  }, []);

  useEffect(() => {
    queryData();
  }, [page, currentTab]);

  const [form] = Form.useForm();
  //初始化搜索区域
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item label="栏目" name="classify">
                <Select
                  placeholder="请选择"
                  options={categoryOptions}
                  // defaultValue={0}
                  allowClear
                  onChange={() => queryData()}
                />
              </Form.Item>
            </Col>

            <Col span={6}>
              <Form.Item label="操作时间" name="dataDate">
                <RangePicker locale={locale} onChange={() => queryData()} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="审核人:" name="reviewerName">
                <Input placeholder="请输入审核人" onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col span={4} className="basic-search-form-submit-btn" style={{ display: 'flex' }}>
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  //查询

  const queryData = async () => {
    let values = form.getFieldsValue();
    if (values.dataDate != null && values.dataDate != undefined) {
      values.timeStart = moment(values.dataDate[0]).format('YYYY-MM-DD') + ' 00:00:00';
      values.timeEnd = moment(values.dataDate[1]).format('YYYY-MM-DD') + ' 23:59:59';
    }
    let msg = {};
    if (Object.values(values).every((i) => !i)) {
      //此时为加载数据
      const params = {
        page: pagination.current,
        pageSize: pagination.pageSize,
      };

      if (currentTab == '1') {
        msg = await getTopicInfoList(params);
        setDataList(msg.data?.list);
      } else if (currentTab == '2') {
        msg = await countByCatName(params);
        // msg = await countByCatName(params);
        setDataList(msg.data);
      } else if (currentTab == '3') {
        msg = await countByGroup(params);
        setDataList(msg.data);
      } else if (currentTab == '4') {
        msg = await countByAuthor(params);
        setDataList(msg.data);
      } else if (currentTab == '5') {
        msg = await countByReviewer(params);
        msg.data = msg.data.map(i=>{

          i.showTm = parseFloat(i.avgReviewTime).toFixed(2)+'天'
          return i
        })
        setDataList(msg.data);
      } else {
        // to be added
        return;
      }
    } else {
      //此时为搜索状态

      const params = {
        page: page,
        pageSize: pagination.pageSize,
        ...values,
      };
      msg = await getTopicInfoList(params);
      setDataList(msg.data.list);
      //搜索结果显示在第一个tab里
      setCurrentTab('1');
      getColumns('1');
    }

    setPagination({ ...pagination, total: msg.data?.total });


  };

  const handleTableChange = (pagination: any) => {
    setPagination(pagination);
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  const renderTable = (key) => {
    return (
      <Table
        key={key}
        actionRef={actionRef}
        rowKey="id"
        search={false}
        tableStyle={{ textAlign: 'center' }}
        options={false}
        onChange={handleTableChange}
        dataSource={dataList}
        columns={columns}
        pagination={pagination}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
    );
  };
  const onChange = (key: string) => {
    // setDataList([]);
    getColumns(key);
    setCurrentTab(key);
    //重制分页
    form.resetFields();
    setPagination({
      current: 1,
      pageSize: 10,
      position: ['bottomRight'],
      size: 'small',
      showSizeChanger: true,
      total: 40,
    });
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `查询结果`,
      children: renderTable(1),
    },
    {
      key: '2',
      label: `按栏目统计`,
      children: renderTable(2),
    },
    {
      key: '3',
      label: `按部门统计`,
      children: renderTable(3),
    },
    {
      key: '4',
      label: `按作者统计`,
      children: renderTable(4),
    },
    {
      key: '5',
      label: `按审核人统计`,
      children: renderTable(5),
    },
  ];

  return (
    <PageContainer header={{ title: false }}>
      {_initSearchForm()}

      <div className="tabContent">
        {
          isFlow? <Tabs defaultActiveKey="1" items={items} onChange={onChange} activeKey={currentTab} />:
            <div className={'nullClass'}>暂未开启流量统计</div>

        }

      </div>
    </PageContainer>
  );
};

export default TableList;
